﻿/*
 * Created by SharpDevelop.
 * User: yeang-shing.then
 * Date: 11/2/2012
 * Time: 1:26 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using KCLIMTrading.Mgmt;

namespace KCLIMTrading
{
	/// <summary>
	/// Description of ProductForm.
	/// </summary>
	public partial class ProductForm : Form
	{
		private B2BManager manager;
		
		public ProductForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
		}
		/// <summary>
		/// Recommended constructor.
		/// </summary>
		/// <param name="manager"></param>
		public ProductForm(B2BManager manager)
		{
			InitializeComponent();
			
			this.manager = manager;
			System.Diagnostics.Debug.WriteLine("Product found: "+manager.Database.Products.Count);
			dataGrid1.DataSource = manager.Database.Products;
			toolStripStatusLabel1.Text = "Total: "+manager.Database.Products.Count;
		}
		
		#region Methods
		private void Retrieve(int index)
		{
			System.Diagnostics.Debug.WriteLine("retrieving row "+index);
			textBox2.Text = manager.Database.Products[index].Code;
			textBox3.Text = manager.Database.Products[index].Name;
			numericUpDown1.Value = manager.Database.Products[index].Price;
		}		
		private void Reset()
		{
			textBox2.Text = string.Empty;
			textBox3.Text = string.Empty;
			numericUpDown1.Value = 0;
		}
		private void Add()
		{
			Product product = new Product();
			product.Code = textBox2.Text.Trim();
			product.Name = textBox3.Text.Trim();
			product.Price = numericUpDown1.Value;

			manager.Database.Add(product);
			dataGrid1.DataSource = null;
			dataGrid1.DataSource = manager.Database.Products;
		}
		private void Delete(int i)
		{
			manager.Database.Products.RemoveAt(i);
			dataGrid1.DataSource = null;
			dataGrid1.DataSource = manager.Database.Products;
		}
		private void Find(string key)
		{
			SortableBindingList<Product> source = (SortableBindingList<Product>)dataGrid1.DataSource;
			int index = source.FindLike("Name",key);
			if(index > -1)
			{
				dataGrid1.CurrentRowIndex = index;
				Retrieve(index);
			}
		}
		#endregion
		
		#region Events
		void TextBox1KeyDown(object sender, KeyEventArgs e)
		{
			if(e.KeyCode == Keys.Enter)
				Find((sender as TextBox).Text);
		}
		void PictureBox1Click(object sender, EventArgs e)
		{
			Find(textBox1.Text);
		}
		
		void Button2Click(object sender, EventArgs e)
		{
			Reset();
		}
		void Button1Click(object sender, EventArgs e)
		{
			Add();
		}
		void Button3Click(object sender, EventArgs e)
		{
			Delete(dataGrid1.CurrentRowIndex);
		}
		void DataGrid1MouseUp(object sender, MouseEventArgs e)
		{
			Retrieve((sender as DataGrid).CurrentRowIndex);
		}
		#endregion
	}
}